import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/eventbus/EventRefreshPart.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/views/Controller/RuleController.dart';
import 'package:yuellyfactory/views/base/RuleView.dart';
import 'package:yuellyfactory/views/dto/PriceParm.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PricePart.dart';


class ParmVC extends StatefulWidget {
  final VoidCallback callback;
  final PricePart pricePart;
  final PriceParm priceParm;
  const ParmVC({super.key, required this.callback, required this.pricePart, required this.priceParm});

  @override
  State<ParmVC> createState() => _ParmVCState();
}

class _ParmVCState extends State<ParmVC> {

  final formKey = GlobalKey<ShadFormState>();

  final RuleController ruleController=RuleController();

  PriceParm? priceParm;

  final selectRequired = {
    '0': '非必填',
    '1': '必填',
  };
  final selectHandle= {
    '0': '输入数据',
    '1': '录入公式',
  };

  List settingRules=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    priceParm=widget.priceParm;
    ruleController.settingRules=(List data){
      debugPrint("回调");
      settingRules=data;
    };
  }
  @override
  Widget build(BuildContext context) {
    return

      ShadSheet(
      onClosing: (){
        debugPrint("关闭回调");
        widget.callback();
      },
        constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),
        title: Row(
          children: [
            const Text('参数编辑'),
            const SizedBox(width: 50,),
            ViewUtil.doneIcon("保存", (){
              submit();
            })
          ],
        ),
      description: const Text(
          "编辑每一个参数的属性"),
      child:  ShadForm(
          key: formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [

              Row(
                children: [
                  Expanded(child: ShadInputFormField(
                    id: 'name',
                    initialValue: priceParm!.name,
                    label: const Text('参数名称'),
                    placeholder: const Text('请输入参数名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入参数名称';
                      }
                      return null;
                    },
                  ),),
                  SizedBox(width: ViewUtil.screenWidth(10),),
                  Expanded(child: ShadInputFormField(
                    id: 'unit',
                    initialValue: priceParm!.unit,
                    label: const Text('单位'),
                    placeholder: const Text('请输入单位'),
                    // validator: (v) {
                    //   if (v.isEmpty) {
                    //     return '请输入单位';
                    //   }
                    //   return null;
                    // },
                  ),),
                ],
              ),


              const SizedBox(height: 10),

              Row(
                children: [
                  Expanded(child:  ShadSelectFormField<String>(
                    id: 'required',

                    label: const Text('是否必填'),
                    minWidth: 350,
                    onChanged: handleChangeRequire,
                    initialValue: priceParm!.required.toString(),
                    options:[...selectRequired.entries
                        .map((e) => ShadOption(value: e.key, child: Text(e.value))),],
                    selectedOptionBuilder: (context, value) => value == 'none'
                        ? const Text('请选择是否必填')
                        : Text(selectRequired[value]!),
                    placeholder: const Text('是否必填'),
                    validator: (v) {
                      if (v == null) {
                        return '请选择是否必填';
                      }
                      return null;
                    },
                  ),),
                  const SizedBox(width: 10,),
                  Expanded(child: ShadSelectFormField<String>(
                    id: 'handle',

                    label: const Text('录入方式'),
                    minWidth: 350,

                    initialValue: priceParm!.handle.toString(),
                    onChanged: handleChange,
                    options:[...selectHandle.entries
                        .map((e) => ShadOption(value: e.key, child: Text(e.value))),],
                    selectedOptionBuilder: (context, value) => value == 'none'
                        ? const Text('请选择录入方式')
                        : Text(selectHandle[value]!),
                    placeholder: const Text('录入方式'),
                    validator: (v) {
                      if (v == null) {
                        return '请选择录入方式';
                      }
                      return null;
                    },
                  ),)
                ],
              ),
              const SizedBox(height: 10),
              Visibility(
                maintainState: true,
                  visible:  priceParm!.handle==0,
                  child: ShadInputFormField(
                id: 'value',
                initialValue: widget.priceParm.value,
                label: const Text('录入数据(显示)'),
                placeholder: const Text('请输入'),
                validator: (v) {
                  if (priceParm!.handle==0&&priceParm!.required==1&&v.isEmpty) {
                    return '请输入';
                  }
                  return null;
                },
              )),
              Visibility(
                maintainState: true,
                  visible:  priceParm!.handle==1,
                  child: RuleView(widget.pricePart, ruleController,priceParm!,type:0)),









              const SizedBox(height: 16),


              // Row(
              //   mainAxisAlignment: MainAxisAlignment.center,
              //   children: [ViewUtil.textButton('保存', ViewUtil.screenWidth(400), ViewUtil.screenHeight(30), ViewUtil.radio(15),
              //       ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
              //         submit();
              //       }),],
              // ),
            ],
          )),
    );
  }

  void handleChange(var value){
    debugPrint(value);
    priceParm!.handle=int.parse(value.toString());
    setState(() {
      
    });
  }

  void handleChangeRequire(var value){
    debugPrint(value);
    priceParm!.required=int.parse(value.toString());
    setState(() {

    });
  }


  void submit(){
    if (formKey.currentState!.saveAndValidate()) {


      var values= formKey.currentState!.value;
      var name=values["name"];
      var parentId=priceParm!.parentId;
      var value=values["value"];
      var unit=values["unit"];
      var required=values["required"];
      var handle=priceParm!.handle;
      if(handle==1){

        if(settingRules.isEmpty){
          ToastUtil.showToast('请编辑公式');
          return;
        }
      }

      var id=widget.priceParm.id.isEmpty?null:widget.priceParm.id;
      var parm={
        "name":name,
        "parentId":parentId,
        "value":value,
        "unit":unit,
        "required":required,
        "handle":handle,
        "id":id,
        "rule":settingRules,


      };

      BaseRequest.postHttp("price/editpartparm",parameters: parm, canTip: true, context: context, onSuccess: (data){

        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          eventBus.fire(EventRefreshPart());
        }
        Navigator.pop(context);
      }, onError: (error){

      });
    }

    }

}
